package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"medical/models"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type DrugController struct {
	beego.Controller
}

type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// 文件上传

func (c *DrugController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close() //关闭文件
	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "文件过大，请重新上传",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	ext := map[string]bool{
		".png":  true,
		".jpg":  true,
		".jpeg": true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if !ext[suffix] {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "文件类型错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		imgSrc := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "文件上传成功",
			Data: imgSrc,
		}
		c.ServeJSON()
	}

}

// 药品添加

func (c *DrugController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	info := c.GetString("info")
	cate := c.GetString("cate")
	status := c.GetString("status")
	img := c.GetString("img")
	drug := models.Drug{
		Name:   name,
		Price:  price,
		Info:   info,
		Cate:   cate,
		Status: status,
		Img:    img,
	}
	err := models.DB.Create(&drug).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

}

// 药品列表

func (c *DrugController) List() {

	pageData := make(map[string]interface{}) //大容器
	query := models.DB.Model(&models.Drug{}) // 查询构建器

	page, _ := c.GetInt("page", 1) //当前页
	size, _ := c.GetInt("size", 5) //每页条数

	name := c.GetString("name") //名称
	cate := c.GetString("cate") //分类
	// 多条件查询
	if name != "" {
		// 模糊匹配
		query = query.Where("name like ?", "%"+name+"%")
	}
	if cate != "" {
		// 完全匹配
		query = query.Where("cate = ?", cate)
	}
	key := "page-" + strconv.Itoa(page) + "-" + name + "-" + cate
	// 判断缓存中是否有数据
	val, err := models.Rdb.Get(key).Result()

	if err != nil {
		var count int64
		query.Count(&count)
		var drugs []models.Drug
		offset := (page - 1) * size
		err = query.Offset(offset).Limit(size).Find(&drugs).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			pageData["count"] = count
			pageData["drugs"] = drugs
			jsonByte, _ := json.Marshal(&pageData)
			value := string(jsonByte)
			models.Rdb.Set(key, value, time.Minute*3)
			c.Data["json"] = JsonRes{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: pageData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()

	}

}

// 药品删除

func (c *DrugController) Delete() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Drug{}, id).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

// 药品详情

func (c *DrugController) Info() {
	// 判断缓存中是否有数据，如果有直接读取缓存，如果没有则读取数据库，并添加到缓存
	id, _ := c.GetInt("id")
	key := "drug-" + strconv.Itoa(id) // drug-2
	val, err := models.Rdb.Get(key).Result()
	RankKey := "drug-rank"
	var drug models.Drug
	if err != nil {
		err = models.DB.Where("id = ?", id).First(&drug).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 0,
				Msg:  "详情查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			// 浏览次数+1
			models.Rdb.ZIncrBy(RankKey, 1, drug.Name)
			// 添加缓存
			jsonByte, _ := json.Marshal(&drug)
			value := string(jsonByte)
			models.Rdb.Set(key, value, time.Minute*3)

			c.Data["json"] = JsonRes{
				Code: 200,
				Msg:  "详情查询成功-mysql",
				Data: drug,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &drug)
		// 浏览次数+1
		models.Rdb.ZIncrBy(RankKey, 1, drug.Name)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "详情查询成功-redis",
			Data: drug,
		}
		c.ServeJSON()
	}

}

// 药品修改

func (c *DrugController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	info := c.GetString("info")
	cate := c.GetString("cate")
	status := c.GetString("status")
	img := c.GetString("img")
	drug := models.Drug{
		Name:   name,
		Price:  price,
		Info:   info,
		Cate:   cate,
		Status: status,
		Img:    img,
	}
	err := models.DB.Where("id = ?", id).Updates(&drug).Error
	// update drugs set name = '感冒颗粒',price = 100  where id = 2
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

// 状态修改

func (c *DrugController) UpdateDrugStatus() {
	id, _ := c.GetInt("id")
	status := c.GetString("status")
	drug := models.Drug{
		Status: status,
	}
	err := models.DB.Where("id = ?", id).Updates(&drug).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

// 排行榜

func (c *DrugController) Rank() {
	key := "drug-rank"
	nums := models.Rdb.ZCard(key).Val() //17
	ranks, err := models.Rdb.ZRevRangeWithScores(key, 0, nums-1).Result()
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "展示成功",
			Data: ranks,
		}
		c.ServeJSON()
	}
}
